import axios from "axios";
import {message} from "antd";
import {getToken} from "../utils/tokenUtils";
const instance = axios.create(
    {
        timeout:10*1000
    }
)

instance.interceptors.response.use(
    (response) => {
        const resData = (response.data || {}) as ResType;
        // console.log(JSON.stringify(resData))
        const { code, data, msg } = resData;
        if (code !== 200) {
            if (msg) {
                message.error(msg);
            }
             throw new Error(msg);
        }
        return data as any;
    }
);

export type ResType = {
    code: number;
    data?: ResDataType;
    msg?: string;
};
export type ResDataType = {
    [key: string]: any;
};

//对request请求的拦截
instance.interceptors.request.use(
    config => {
        config.headers['Authorization'] =`Bearer ${getToken()}`;
        return config;
    },
    error => {
        Promise.reject(error);
    }
)

//
// //对网络请求的拦截
// instance.interceptors.response.use(
//     res =>{
//
//       console.log("Helllllllllllll")
//
//         const resData = (res.data || {}) as ResType;
//         //res.data 才是具体的{}的数据
//         const {code,data,msg} = resData;
//         if (code !== 200) {
//             if (msg) {
//                 message.error(msg);
//             }
//             throw  new Error(msg);
//         }
//
//         return data as any;
//     }
// )
//
//
//
// export type ResType = {
//     code:number,
//     data?:ResDataType,
//     msg?:string
// }
// export type ResDataType={
//     [key:string]:any
// }

export default instance;